from django.db import models


class BaseModel(models.Model):
    """模型抽象基类"""
    is_delete = models.BooleanField(default=False, verbose_name='删除标记')

    class Meta:
        # 说明是一个抽象模型类
        abstract = True


class Permission(BaseModel):
    url = models.CharField(max_length=64)
    title = models.CharField(max_length=20)

    class Meta:
        db_table = 'permission'


class Role(BaseModel):
    name = models.CharField(max_length=64)
    permissions = models.ManyToManyField(Permission)
    status = models.BooleanField(default=True)

    class Meta:
        db_table = 'role'

    def to_json(self):
        return {
            'id': self.id,
            'name': self.name,
            'permissions': self.permissions,
            'status': self.status
        }        


class User(BaseModel):
    username = models.CharField("用户名", max_length=64)
    password = models.CharField("密码", max_length=200)
    is_superuser = models.BooleanField("是否超级管理员", default=False)
    roles = models.ManyToManyField(Role, related_name='users')
    create_time = models.DateTimeField(auto_now_add=True)
    update_time = models.DateTimeField(auto_now=True)
    phone = models.CharField(verbose_name='手机号', max_length=11)

    class Meta:
        db_table = 'user'

    def to_json(self):
        return {
            'id': self.id,
            'username': self.username,
            'phone': self.phone,
            'create_time': self.create_time,
            'update_time': self.update_time
        }
